package com.qf.ssm.pay.thread;

import com.qf.ssm.pay.pojo.Orders;
import com.qf.ssm.pay.service.MerchantService;
import com.qf.ssm.pay.service.OrdersService;
import com.qf.ssm.pay.util.HttpUtil;
import com.qf.ssm.pay.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;

public class CallbackThread implements Runnable {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private MerchantService merchantService;
    private boolean running = false;
    @PostConstruct
    public void start() {
        if (!this.running) {
            this.running = true;
        }
        SendHandler handler = new SendHandler();
        Thread thread = new Thread(handler);
        thread.start();
    }

    class SendHandler implements Runnable {
        public void run() {
            while (running) {
                List<Orders> orders = ordersService.getNotNotifyOrderList();
                for (Orders order : orders) {
                    String url = order.getNotifyURL();
                    //md5(orderId=xxx&price=xxxx&merchantId=xxx&notifyURL=xxxx&otherParam=xxx+secretKey)
                    StringBuilder sb = new StringBuilder();
                    sb.append("orderId=").append(order.getOrderId());
                    sb.append("&tradeNum=").append(order.getTradeNum());
                    sb.append("&price=").append(order.getPrice());
                    sb.append("&merchantId=").append(order.getMerchantId());
                    sb.append("&otherParam=");
                    if (!StringUtils.isEmpty(order.getOtherParam())) {
                        sb.append(order.getOtherParam());
                    }
                    String params = sb.toString();
                    String secretKey = merchantService.getScretKeyById(order.getMerchantId());
                    sb.append(secretKey);
                    //自己计算出的签名
                    String signStr = MD5Util.getMD5(sb.toString());
                    params += "&sign=" + signStr;
                    String result = HttpUtil.doPost(url, params);
                    System.err.println(result);
                    if ("ok".equals(result)) {
                        order.setPayStatus(1);
                    } else {
                        if (order.getNotifyTimes() >= 9) {
                            order.setPayStatus(-1);
                        } else {
                            order.setPayStatus(0);
                        }
                    }
                    ordersService.updateStatus(order);
                }
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

    }
    @Override
    public void run() {

    }
}
